package com.uft.security.tam.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.uft.utils.UftUtils;



public class UserDetailsServiceImpl implements UserDetailsService {
	 private  static Logger  logger = Logger.getLogger(UserDetailsServiceImpl.class);
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		
		UserDetails user= new User(username,
				"",
				true,
				true,
				true,
				true,
				getGrantedAuthorities(username));
		
		return user;
	}

	private Collection<? extends GrantedAuthority> getGrantedAuthorities(
			String username) {
		List<String> groups= new ArrayList<String>();
		groups.add("WebSphereConsoleUsers");
		String ivgroups="WebSphereConsoleUsers";
		
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
		
//		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
//		HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
//		
		Enumeration  enames = request.getHeaderNames();
		while (enames.hasMoreElements()) {
			String name = (String) enames.nextElement();
			String value = request.getHeader(name);
			logger.debug("Header Name: "+name+" value: "+value);
		}
		
		logger.info("request: "+request);
		String ivUser=(String) request.getHeader(AutoLoginFilter.principalUserRequestHeader);
		logger.info("iv-user: "+ivUser);
		ivgroups=(String) request.getHeader(AutoLoginFilter.principalGroupRequestHeader);
		logger.info("iv-group: "+ivgroups);
		
		
		Collection<GrantedAuthority> clc= new ArrayList<GrantedAuthority>();
		if(UftUtils.isAdministrator(ivgroups, groups)){
			GrantedAuthorityImpl grt2= new GrantedAuthorityImpl("ROLE_ADMIN");
			clc.add(grt2);
		}
		GrantedAuthorityImpl grt1= new GrantedAuthorityImpl("ROLE_USER");
		
		clc.add(grt1);
		
		// TODO Auto-generated method stub
		return clc;
	}
	

}
